﻿    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Diagnostics;
using Microsoft.TeamFoundation.Build.Client;

namespace TeamDeploy.Activities
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public sealed class RemoteExecute : CustomActivityBase
    {
        [RequiredArgument]
        public InArgument<string> TargetMachine { get; set; }

        [RequiredArgument]
        public InArgument<string> RemoteCommand { get; set; }

        [RequiredArgument]
        public InArgument<string> RemoteExecutePathFilename { get; set; }

        public InArgument<string> OptionalParamters { get; set; }

        public InArgument<bool> WaitForExit { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {

            try
            {
                string targetMachine = context.GetValue(this.TargetMachine);
                string remoteCommand = context.GetValue(this.RemoteCommand);
                string remoteExecutePathFilename = context.GetValue(this.RemoteExecutePathFilename);
                string optionalParameters = context.GetValue(this.OptionalParamters);
                bool waitForExit = context.GetValue(this.WaitForExit);

                bool ignoreExitCode = false;
                bool.TryParse(context.GetValue(this.IgnoreExitCode), out ignoreExitCode);

                if (!System.IO.File.Exists(remoteExecutePathFilename))
                {
                    //Log.LogError("RemoteExecute does not exists at: " + remoteExecutePathFilename);
                    return;
                }

                string options = " -i 0 -s -accepteula ";
                if (!waitForExit)
                    options += "-d ";

                string args = @"\\" + targetMachine + options + remoteCommand + " " + optionalParameters;



                //Process p = Process.Start(remoteExecutePathFilename, args);

                using (System.Diagnostics.Process process = new System.Diagnostics.Process())
                {
                    process.StartInfo.FileName = remoteExecutePathFilename;
                    //process.StartInfo.WorkingDirectory = SearchPathRoot.Get(context);                    
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.ErrorDialog = false;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.Arguments = args;

                    try
                    {
                        process.Start();
                        string output = process.StandardOutput.ReadToEnd();

                        LogMessage(context, "RemoteExecute Output:" + output);
                    }
                    catch (Exception ex)
                    {
                        LogMessage(context, ex.ToString());
                        throw ex;
                    }

                    if (waitForExit)
                    {
                        process.WaitForExit();

                        if (process.ExitCode != 0)
                        {
                            string message = "Executing " + remoteCommand + " on " + targetMachine + " returned code:" + process.ExitCode;

                            if (ignoreExitCode)
                            {
                                LogMessage(context, message);
                            }
                            else
                            {
                                // Log.LogError(message);
                                // return false;  
                                throw new Exception(message);
                            }
                        }
                    }
                }
  
                LogMessage(context, "Executing " + RemoteCommand + " on " + TargetMachine + " completed successfully.");

            }
            catch(Exception)
            {
                throw;
            }
        }
    }
}